<?php

/**
 * @property CI_Loader $load
 * @property CI_Form_validation $form_validation
 * @property CI_Input $input
 * @property CI_Email $email
 * @property CI_DB_active_record $db
 * @property CI_DB_forge $dbforge
 */
class Catagory_model extends CI_Model {

    /**
     * table name for the catagory using left-right sort
     * @var <type> 
     */
    var $table;

    public function __construct() {
        parent::__construct();
    }

    public function set_table($TableName) {
        $this->table = $TableName;
    }

    private function update_layer() {
        // update  sm_catagory set Layer = CountLayer(CatagoryID);
        $this->db->set('Layer', 'CountLayer(CatagoryID)', FALSE);
        $this->db->update($this->table);
    }

    /**
     * Short description.
     * 增加新的分类
     * Detail description
     * @param         none
     * @global         none
     * @since         1.0
     * @access         private
     * @return         void
     * @update         date time
     */
    public function add_catagory($CatagoryID, $SortName) {
        if ($CatagoryID == 0) {
            $Lft = 0;
            $Rgt = 1;
            $layer = 1;
        } else {
            $Result = $this->check_catagory($CatagoryID);
            //取得父类的左值,右值
            $Lft = $Result['Lft'];
            $Rgt = $Result['Rgt'];
            $layer = $Result['Layer'];

            $this->db->set('Lft', 'Lft+2', FALSE);
            $this->db->where('Lft >', $Rgt);
            $this->db->update($this->table);
            // $this->db->query("UPDATE " . $this->tablefix . "catagory SET Lft=Lft+2 WHERE Lft>$Rgt");

            $this->db->set('Rgt', 'Rgt+2', FALSE);
            $this->db->where('Rgt >=', $Rgt);
            $this->db->update($this->table);
            // $this->db->query("UPDATE " . $this->tablefix . "catagory SET Rgt=Rgt+2 WHERE Rgt>=$Rgt");
        }

        //插入
        $this->db->set(array('Lft' => $Rgt, 'Rgt' => $Rgt + 1, 'Name' => $SortName, 'Layer' => $layer));
        $this->db->insert($this->table);
        // if ($this->db->query("INSERT INTO " . $this->tablefix . "catagory SET Lft='$Rgt',Rgt='$Rgt'+1,Name='$SortName'")) {
        if ($this->db->affected_rows() > 0) {
            //$this->referto("成功增加新的类别","JAVASCRIPT:HISTORY.BACK(1)",3);
            $this->update_layer();
            return 1;
        } else {
            //$this->referto("增加新的类别失败了","JAVASCRIPT:HISTORY.BACK(1)",3);
            return -1;
        }
    }

    /**
     * Short description.
     * 删除类别
     * Detail description
     * @param         none
     * @global         none
     * @since         1.0
     * @access         private
     * @return         void
     * @update         date time
     */
    public function delete_catagory($CatagoryID) {
        //取得被删除类别的左右值,检测是否有子类,如果有就一起删除
        $Result = $this->check_catagory($CatagoryID);
        $Lft = $Result['Lft'];
        $Rgt = $Result['Rgt'];
        //执行删除
        $this->db->delete($this->table, array('Lft >=' => $Lft, 'Rgt <=' => $Rgt));
        // if ($this->db->query("DELETE FROM " . $this->tablefix . "catagory WHERE Lft>=$Lft AND Rgt<=$Rgt")) {
        if ($this->db->affected_rows() > 0) {
            $Value = $Rgt - $Lft + 1;
            //更新左右值
            $this->db->set('Lft', "Lft-$Value", FALSE);
            $this->db->where('Lft >', $Lft);
            $this->db->update($this->table);
            // $this->db->query("UPDATE " . $this->tablefix . "catagory SET Lft=Lft-$Value WHERE Lft>$Lft");

            $this->db->set('Rgt', "Rgt-$Value", FALSE);
            $this->db->where('Rgt >', $Rgt);
            $this->db->update($this->table);
            // $this->db->query("UPDATE " . $this->tablefix . "catagory SET Rgt=Rgt-$Value WHERE Rgt>$Rgt");
            //$this->referto("成功删除类别","javascript:history.back(1)",3);
            return 1;
        } else {
            //$this->referto("删除类别失败了","javascript:history.back(1)",3);
            return -1;
        }
    }

    /**
     * 重命名类别，类别的ID不会改变
     * @param <type> $CatagoryID
     * @param <type> $SorName
     */
    public function ren_catagory($CatagoryID, $SorName){
        $this->db->set('Name', $SorName);
        $this->db->where('CatagoryID', $CatagoryID);
        $this->db->update($this->table);
    }

    /**
     * Short description.
     * 1,所有子类,不包含自己;2包含自己的所有子类;3不包含自己所有父类4;包含自己所有父类
     * Detail description
     * @param         none
     * @global         none
     * @since         1.0
     * @access         private
     * @return         void
     * @update         date time
     */
    function get_catagory($CatagoryID, $type=1) {
        $Result = $this->check_catagory($CatagoryID);
        $Lft = $Result['Lft'];
        $Rgt = $Result['Rgt'];
        // $SeekSQL = "SELECT * FROM " . $this->tablefix . "catagory WHERE ";
        switch ($type) {
            case "1":
                $this->db->where(array('Lft >' => $Lft, 'Rgt <' => $Rgt));
                // $condition = "Lft>$Lft AND Rgt<$Rgt";
                break;
            case "2":
                $this->db->where(array('Lft >=' => $Lft, 'Rgt <=' => $Rgt));
                // $condition = "Lft>=$Lft AND Rgt<=$Rgt";
                break;
            case "3":
                $this->db->where(array('Lft <' => $Lft, 'Rgt >' => $Rgt));
                // $condition = "Lft<$Lft AND Rgt>$Rgt";
                break;
            case "4":
                $this->db->where(array('Lft <=' => $Lft, 'Rgt >=' => $Rgt));
                // $condition = "Lft<=$Lft AND Rgt>=$Rgt";
                break;
            default :
                $this->db->where(array('Lft >' => $Lft, 'Rgt <' => $Rgt));
                // $condition = "Lft>$Lft AND Rgt<$Rgt";
                ;
        }
        $this->db->order_by('Lft', 'asc');
        // $SeekSQL.=$condition . " ORDER BY Lft ASC";
        $Sorts = $this->db->get($this->table)->result_array();
        // $Sorts = $this->db->getrows($SeekSQL);
        return $Sorts;
    }

    /**
     * Short description.
     * 取得直属父类
     * Detail description
     * @param         none
     * @global         none
     * @since         1.0
     * @access         private
     * @return         void
     * @update         date time
     */
    function get_parent($CatagoryID) {
        $Parent = $this->get_catagory($CatagoryID, 3);
        return $Parent;
    }

    /**
     * Short description.
     * 移动类,如果类有子类也一并移动
     * Detail description
     * @param         none
     * @global         none
     * @since         1.0
     * @access         private
     * @return         void
     * @update         date time
     */
    public function move_catagory($SelfCatagoryID, $ParentCatagoryID) {
        $SelfCatagory = $this->check_catagory($SelfCatagoryID);
        $NewCatagory = $this->check_catagory($ParentCatagoryID);


        $SelfLft = $SelfCatagory['Lft'];
        $SelfRgt = $SelfCatagory['Rgt'];
        $Value = $SelfRgt - $SelfLft;
//取得所有分类的ID方便更新左右值
        $CatagoryIDS = $this->get_catagory($SelfCatagoryID, 2);
        foreach ($CatagoryIDS as $v) {
            $IDS[] = $v['CatagoryID'];
        }
        // $InIDS = implode(",", $IDS);

        $ParentLft = $NewCatagory['Lft'];
        $ParentRgt = $NewCatagory['Rgt'];
//print_r($InIDS);
//print_r($NewCatagory);
//print_r($SelfCatagory);
//exit;
        if ($ParentRgt > $SelfRgt) {
            $this->db->set('Lft', "Lft-$Value-1", False);
            $this->db->where(array('Lft >' => $SelfRgt, 'Rgt <=' => $ParentRgt));
            $this->db->update($this->table);
            //$UpdateLeftSQL = "UPDATE " . $this->tablefix . "catagory SET Lft=Lft-$Value-1 WHERE Lft>$SelfRgt AND Rgt<=$ParentRgt";

            $this->db->set('Rgt', "Rgt-$Value-1", false);
            $this->db->where(array('Rgt >' => $SelfRgt, 'Rgt <' => $ParentRgt));
            $this->db->update($this->table);
            // $UpdateRightSQL = "UPDATE " . $this->tablefix . "catagory SET Rgt=Rgt-$Value-1 WHERE Rgt>$SelfRgt AND Rgt<$ParentRgt";


            $TmpValue = $ParentRgt - $SelfRgt - 1;
            $this->db->set('Lft', "Lft+$TmpValue", False);
            $this->db->set('Rgt', "Rgt+$TmpValue", false);
            $this->db->where_in('CatagoryID', $IDS);
            $this->db->update($this->table);
            // $UpdateSelfSQL = "UPDATE " . $this->tablefix . "catagory SET Lft=Lft+$TmpValue,Rgt=Rgt+$TmpValue WHERE CatagoryID IN($InIDS)";
        } else {
            $this->db->set('Lft', "Lft+$Value+1", false);
            $this->db->where(array('Lft >' => $ParentRgt, 'Lft <' => $SelfLft));
            $this->db->update($this->table);
            // $UpdateLeftSQL = "UPDATE " . $this->tablefix . "catagory SET Lft=Lft+$Value+1 WHERE Lft>$ParentRgt AND Lft<$SelfLft";

            $this->db->set('Rgt', "Rgt+$Value+1", False);
            $this->db->where(array('Rgt >=' => $ParentRgt, 'Rgt <' => $SelfLft));
            $this->db->update($this->table);
            // $UpdateRightSQL = "UPDATE " . $this->tablefix . "catagory SET Rgt=Rgt+$Value+1 WHERE Rgt>=$ParentRgt AND Rgt<$SelfLft";

            $TmpValue = $SelfLft - $ParentRgt;
            $this->db->set('Lft', "Lft-$TmpValue", False);
            $this->db->set('Rgt', "Rgt-$TmpValue", False);
            $this->db->where_in('CatagoryID', $IDS);
            $this->db->update($this->table);
            // $UpdateSelfSQL = "UPDATE " . $this->tablefix . "catagory SET Lft=Lft-$TmpValue,Rgt=Rgt-$TmpValue WHERE CatagoryID IN($InIDS)";
        }
        // $this->db->query($UpdateLeftSQL);
        // $this->db->query($UpdateRightSQL);
        // $this->db->query($UpdateSelfSQL);
        //$this->referto("成功移动类别","javascript:history.back(1)",3);
        $this->update_layer();
        return 1;
    }

    /**
     * Short description.
     * 检测父类ID是否存在
     * Detail description
     * @param         none
     * @global         none
     * @since         1.0
     * @access         private
     * @return         void
     * @update         date time
     */
    function check_catagory($CatagoryID) {
        $this->db->where('CatagoryID', $CatagoryID);
        $this->db->limit(1);
        $Result = $this->db->get($this->table)->row_array();
        // $SQL = "SELECT * FROM " . $this->tablefix . "catagory WHERE CatagoryID='$CatagoryID' LIMIT 1";
        // $Result = $this->db->getrow($SQL);
        // if (count($Result) < 1) {
        //     $this->referto("父类ID不存在,请检查", "javascript:history.back(1)", 3);
        // }
        return $Result;
    }

    /**
     * Short description.
     *
     * Detail description
     * @param         none
     * @global         none
     * @since         1.0
     * @access         private
     * @return         void
     * @update         date time
     */
    public function get_rootid() {
        $this->db->order_by('Lft', 'ASC');
        $this->db->limit(1);
        $RootID = $this->db->get($this->table)->row_array();
        // $Query = "SELECT * FROM" . $this->tablefix . "catagory ORDER BY Lft ASC LIMIT 1";
        //$RootID = $this->db->getrow($Query);
        if (count($RootID) > 0) {
            return $RootID['CatagoryID'];
        } else {
            return 0;
        }
    }

    /**
     *
     * @param <type> catagory id
     * @return array(): level=>NodeName
     */
    public function get_tree($root) {
        // 得到节点的左右值
        $this->db->select('Lft, Rgt, Layer');
        $this->db->where('CatagoryID', $root);
        $result = $this->db->get($this->table);

        $row = $result->row_array();
        if (count($row) > 0) {
            // 获得根基点的所有子孙节点
            $layer = $row['Layer'];
            $this->db->select("CatagoryId,Name,Layer-{$layer}+1 as Layer,case when Lft+1 = Rgt then 'Y' else 'N' end IsChild",False);
            $this->db->where('Lft >=', $row['Lft']);
            $this->db->where('Rgt <=', $row['Rgt']);
            $this->db->order_by('Lft', 'ASC');
            $result = $this->db->get($this->table);
            $tree = $result->result_array();
            return $tree;
        } else {
            return array();
        }
    }

}